package com.itany.corejava.code12_线程;

/**
 * @author 石小俊
 * @date 2023年05月15日 16:42
 */
public class Test07_线程间的通信 {
    public static void main(String[] args) {
        Object obj = new Object();
        WaitThread t1 = new WaitThread(obj, "线程1");
        WaitThreadTwo t2 = new WaitThreadTwo(obj, "线程2");
        t1.start();
        t2.start();

        NotifyThread notifyThread = new NotifyThread(obj, "notify线程");
        // notifyThread.start();
        NotifyAllThread notifyAllThread = new NotifyAllThread(obj, "notifyAll");
        notifyAllThread.start();
    }
}

class WaitThread extends Thread {
    private Object obj;
    private String name;

    public WaitThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            System.out.println(name + "释放锁,即将进入等待池");
            try {
                // 设置线程等待时间
                // 到达时间之后自动唤醒
                // obj.wait(3000);
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(name + "执行完成");
    }
}

class WaitThreadTwo extends Thread {
    private Object obj;
    private String name;

    public WaitThreadTwo(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            System.out.println(name + "释放锁,即将进入等待池");
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(name + "执行完成");
    }
}

class NotifyThread extends Thread {
    private Object obj;
    private String name;

    public NotifyThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            // 随机唤醒某一个线程
            // 此时唤醒的是当前对象的等待池中的线程
            // 即:obj对象等待池中的线程
            obj.notify();
            System.out.println("已经随机唤醒了等待池中的某一个线程");
        }
    }
}

class NotifyAllThread extends Thread {
    private Object obj;
    private String name;

    public NotifyAllThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj) {
            obj.notifyAll();
            System.out.println("已经唤醒了等待池中所有的线程");
        }
    }
}